package com.lagou.niancheng.configx.conf;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * com.lagou.niancheng.configx.conf.DataSourceConfiguration
 *
 * @author 大犬
 * @date 2020/5/27
 */
@Configuration
public class DataSourceConfiguration {


    private static final String NAMESPACE = "configx";

    private static final String CONFIG_PATH = "/datasource";

    @Value("${configx.zoo.address}")
    private String zookeeperAddress;


    @Bean
    public ConfigxDataSource configxDataSource() throws Exception {
        // 1.创建zookeeper客户端
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zookeeperAddress)
                .retryPolicy(retryPolicy)
                .namespace(NAMESPACE)
                .build();
        client.start();
        // 2.获取配置，构建一个数据源
        byte[] content = client.getData().forPath(CONFIG_PATH);
        DataSourceMetaData dataSourceMetaData = JSONObject.parseObject(content, DataSourceMetaData.class);
        DruidDataSource druidDataSource = getDataSource(dataSourceMetaData);
        // 3.创建封装数据源
        ConfigxDataSource configxDataSource = new ConfigxDataSource();
        // 4.设置zookeeper监听器
        NodeCache nodeCache = new NodeCache(client, CONFIG_PATH, false);
        NodeCacheListener nodeCacheListener = new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                ChildData currentData = nodeCache.getCurrentData();
                byte[] data = currentData.getData();
                DataSourceMetaData newDataSourceMetaData = JSONObject.parseObject(data, DataSourceMetaData.class);
                System.out.println("数据源配置信息发生变更:" + newDataSourceMetaData);
                DruidDataSource oldDataSource = (DruidDataSource) configxDataSource.getDataSource();
                oldDataSource.close();
                DruidDataSource newDataSource = getDataSource(newDataSourceMetaData);
                // 更换新的数据源
                configxDataSource.setDataSource(newDataSource);
            }
        };
        nodeCache.getListenable().addListener(nodeCacheListener);
        nodeCache.start();
        configxDataSource.setDataSource(druidDataSource);
        return configxDataSource;
    }


    private DruidDataSource getDataSource(DataSourceMetaData dataSourceMetaData) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(dataSourceMetaData.getUsername());
        druidDataSource.setDriverClassName(dataSourceMetaData.getDriverClass());
        druidDataSource.setPassword(dataSourceMetaData.getPassword());
        druidDataSource.setUrl(dataSourceMetaData.getUrl());
        return druidDataSource;
    }
}
